package lion.lel;

import java.lang.reflect.Method;

import lion.dev.fun.Fun;

/**
 * Lel function
 *
 * @author lion
 * @email hl_0074@sina.com
 * @date 2014年4月11日
 */
public class LelFunc implements Fun {

	private Method method;
	private Class<?> paramType;

	public LelFunc(Method method) {

		this.method = method;
		if (method.getParameterTypes().length > 0) {
			paramType = method.getParameterTypes()[0];
		}
	}

	@Override
	public Object exec(Object... args) throws Exception {

		String arg = (String) args[0];
		Object param = toParam(arg);

		return method.invoke(method.getDeclaringClass(), param);
	}

	private Object toParam(String arg) {

		if (paramType == null) { return null; }

		if (CharSequence.class.isAssignableFrom(paramType)) { return arg; }
		if (Integer.TYPE.equals(paramType)) { return Integer.parseInt(arg); }
		if (Short.TYPE.equals(paramType)) { return Short.parseShort(arg); }
		if (Long.TYPE.equals(paramType)) { return Long.parseLong(arg); }
		if (Double.TYPE.equals(paramType)) { return Double.parseDouble(arg); }
		if (Boolean.TYPE.equals(paramType)) { return Boolean.parseBoolean(arg); }

		return arg;
	}
}
